Skip to main content

在 Next 中用 Base Path 指定 Sub-path

使用場景: 某個專案構造是用 CircleCI 把 Next 專案 Build 成靜態檔後,上傳到 S3 的 user/ 資料夾中。
這時發現被 build 出來的靜態資源檔諸如各種 js 檔案和 css 檔案都沒有正確引入。
原因是因為 React 自動產生的
https://example.com/_next/static/....
檔案和實際存放位置
https://example.com/user/_next/static/....
有出入造成。

語法

// next.config.js
module.exports = {
basePath: "/docs",
};

效果

當設定 Base Path 為 /docs

export default function HomePage() {
return (
<>
<Link href="/about">
<a>About Page</a>
</Link>
</>
);
}

會生成

<a href="/docs/about">About Page</a>

使用 next/image Component 時需要顯性指定

import Image from "next/image";

function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
// 這裡必須把 sub path 寫進 src 中
src="/docs/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
<p>Welcome to my homepage!</p>
</>
);
}

export default Home;

資料來源

next.config.js: Base Path | Next.js